package com;

import com.example.grpc.HelloRequest;
import com.example.grpc.HelloResponse;
import com.example.grpc.HelloServiceGrpc;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.interceptor.HeaderClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import javax.annotation.Nullable;
import java.util.concurrent.TimeUnit;

/**
 * 基于 Future 的异步 RPC 调用
 */
public class FutureGrpcClient1 {

    public static void main(String[] args) throws InterruptedException {

        // 客户端连接通道
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081)
                .usePlaintext()
                .build();

        HelloServiceGrpc.HelloServiceFutureStub futureStub = HelloServiceGrpc.newFutureStub(channel);


        HelloRequest helloRequest = HelloRequest.newBuilder()
                .setName("Tom")
                .setAge(18)
                .addHobbies("read")
                .putTags("tag", "money")
                .build();

        ListenableFuture<HelloResponse> listenableFuture = futureStub.withInterceptors(new HeaderClientInterceptor()).hello(helloRequest);


        //添加回调，获取返回结果
        Futures.addCallback(listenableFuture, new FutureCallback<HelloResponse>() {
            @Override
            public void onSuccess(@Nullable HelloResponse result) {
                // 解析成功结果
                System.out.println("dddd");
                System.out.println(result);
            }

            @Override
            public void onFailure(Throwable t) {
                // 打印失败信息
                t.printStackTrace();
            }
        });

        // 防止线程过早退出
        Thread.sleep(9_000);
        channel.shutdown().awaitTermination(6, TimeUnit.SECONDS);

    }
}